package com.tripreset.todo

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import com.android.bonn.fast.adapter.CellView
import com.android.bonn.fast.adapter.SimpleCellDelegateAdapter
import com.android.bonn.fast.adapter.ext.create
import com.android.bonn.fast.adapterlayout.AdapterLayout
import com.tripreset.todo.databinding.ActivityMainBinding
import com.tripreset.todo.databinding.ItemTodoLayoutBinding

class MainActivity : AppCompatActivity() {

    private lateinit var adapter: SimpleCellDelegateAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding = ActivityMainBinding.inflate(layoutInflater)

        setContentView(binding.root)
        val todoDao = TodoDaoProvider.todoDao()

        adapter = SimpleCellDelegateAdapter
            .Builder()
            .create(R.layout.item_todo_layout, { ItemCellView(it) })
            .build()
        binding.todoListView.adapter = adapter
        adapter.submitList(mutableListOf<TodoEntity>())

        binding.uiAddTodo.setOnClickListener {
            binding.todoListView.clearFocus()
            adapter.submitList.add(TodoEntity())
            adapter.notifyItemRangeInserted(adapter.itemCount - 1, 1)
        }
    }

    inner class ItemCellView(view: View) : CellView<TodoEntity>(view) {

        private val itemBinding = ItemTodoLayoutBinding.bind(itemView)

        init {

            itemBinding.uiTodoDelete.setOnClickListener {
                val adapterPosition = AdapterLayout.getAdapterPosition(this)
                currentAdapter.submitList.removeAt(adapterPosition)
                currentAdapter.notifyItemRemoved(adapterPosition)
            }
        }

        override fun onBind(entity: TodoEntity, position: Int) {
            itemBinding.uiTodoContent.doAfterTextChanged { text ->
                entity.content = text?.toString() ?: ""
            }

            if (position == currentAdapter.itemCount - 1) {
                itemBinding.uiTodoContent.requestFocus()
            }
        }

    }
}